package com.github.caijh.mall.store.service.impl;

import java.util.List;
import javax.annotation.Resource;
import javax.inject.Inject;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.caijh.commons.util.DateUtils;
import com.github.caijh.mall.constants.Constants;
import com.github.caijh.mall.store.dao.StoreProductAttrResultDao;
import com.github.caijh.mall.store.model.StoreProduct;
import com.github.caijh.mall.store.model.StoreProductAttrResult;
import com.github.caijh.mall.store.request.StoreProductAttrValueRequest;
import com.github.caijh.mall.store.service.StoreProductAttrResultService;
import com.github.caijh.mall.system.service.SystemAttachmentService;
import org.springframework.stereotype.Service;

@Service
public class StoreProductAttrResultServiceImpl extends ServiceImpl<StoreProductAttrResultDao, StoreProductAttrResult>
        implements StoreProductAttrResultService {

    @Resource
    private StoreProductAttrResultDao dao;

    @Inject
    private SystemAttachmentService systemAttachmentService;


    @Override
    public void deleteByProductId(int productId, int type) {
        LambdaQueryWrapper<StoreProductAttrResult> lmdQ = Wrappers.lambdaQuery();
        lmdQ.eq(StoreProductAttrResult::getProductId, productId).eq(StoreProductAttrResult::getType, type);
        dao.delete(lmdQ);
    }

    /**
     * 根据商品属性值集合查询
     *
     * @param storeProductAttrResult 查询参数
     * @return 查询结果
     */
    @Override
    public List<StoreProductAttrResult> getByEntity(StoreProductAttrResult storeProductAttrResult) {
        LambdaQueryWrapper<StoreProductAttrResult> lqw = Wrappers.lambdaQuery();
        lqw.setEntity(storeProductAttrResult);
        return dao.selectList(lqw);
    }

    @Override
    public void updateStoreProductAttrResult(StoreProduct storeProduct, List<StoreProductAttrValueRequest> storeProductAttrValueRequests) {
        this.deleteByProductId(storeProduct.getId(), Constants.PRODUCT_TYPE_NORMAL);
        StoreProductAttrResult attrResult = new StoreProductAttrResult(
                0,
                storeProduct.getId(),
                systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValueRequests)),
                ((int) DateUtils.currentTimestamp()), Constants.PRODUCT_TYPE_NORMAL);
        this.save(attrResult);
    }

}

